package com.enjoy.book.action;

import com.enjoy.book.bean.User;
import com.enjoy.book.biz.UserBiz;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user.let")
public class UserServlet extends HttpServlet {

    // 构建UserBiz的对象
    UserBiz userBiz = new UserBiz();
    @Override
    // 重写HttpServlet中的doGet方法
    // 改为调用doPost方法
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    /**
     * /user.let?type=login 登录  /：项目的根目录:web
     * web
     *    |-login.html
     *    |-user.let?type = login
     *    |-index.jsp
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    // 重写HttpServlet中的doPost方法
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置编码规范
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();

        // 1.判断用户请求的类型为login
        String method = req.getParameter("type");
        switch (method){
            case"login":

                // 2.从login.html中获取用户输入的用户名和密码
                String name = req.getParameter("name");
                String pwd = req.getParameter("pwd");

                // 3.调用UserBiz的getUser方法，根据用户名和密码获取相应的用户对象
                User user = userBiz.getUser(name,pwd);

                // 4.判断用户对象是否为null
                if(user==null){
                    out.println("<script>alert('用户名或密码不存在');location.href = 'login.html';</script>");
                }else{
                    out.println("<script>alert('登录成功');location.href='index.jsp';</script>");
                }
                break;
        }
    }
}
